package com.gxa.saas.portal.controller.luoj;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.gxa.saas.core.common.JsonResult;
import com.gxa.saas.core.entity.dto.luoj.ProductDTO;
import com.gxa.saas.core.entity.dto.luoj.SecKillDTO;
import com.gxa.saas.core.entity.dto.luoj.SecKillInfoDTO;
import com.gxa.saas.core.entity.vo.luoj.SecKillInfoVO;
import com.gxa.saas.core.entity.vo.luoj.SecKillVO;
import com.gxa.saas.core.exception.BusinessException;
import com.gxa.saas.portal.service.SeckillService;
import com.gxa.saas.portal.thread.UserThreadLocal;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/seckill")
@Api(value = "秒杀")
public class SecKillController {

    @Resource
    private SeckillService seckillService;

    @ApiOperation("秒杀")
    @PostMapping("/doSecKill")
    public Map doSecKill(@RequestBody SecKillInfoVO secKillVO) throws BusinessException, JsonProcessingException {
        JsonResult jsonResult = new JsonResult();
        if (secKillVO.getUserId() == null) {
            jsonResult.setCode("0");
            jsonResult.setMsg("请登录");
        } else {
            SecKillVO one = seckillService.getOne(new QueryWrapper<SecKillVO>().eq("user_id",secKillVO.getUserId())
                    .eq("goods_id",secKillVO.getGoodsId()));
            if (one==null) {
                //TODO
                Boolean success = seckillService.seckill(secKillVO.getUserId(),secKillVO.getGoodsId());
                jsonResult.setCode("200");
                if (success) {
                    jsonResult.setMsg("恭喜，秒杀成功");
                } else {
                    jsonResult.setMsg("遗憾，秒杀失败");
                }
            }
            else{
                jsonResult.setMsg("每个账户限制一次");
            }
        }
        return jsonResult.getMap();
    }

    @ApiOperation("查看秒杀商品")
    @GetMapping("/preSecKill")
    public Map preSecKill(){
        JsonResult jsonResult = new JsonResult();
        List<SecKillDTO> secKill = seckillService.getSecKill();
        jsonResult.setCode("200");
        jsonResult.setData(secKill);
        jsonResult.setMsg("查看成功！");
        return jsonResult.getMap();
    }

    @ApiOperation("添加秒杀商品")
    @GetMapping("/addSeckill")
    public Map addSeckill(@RequestBody SecKillDTO secKillDTO){
        JsonResult jsonResult = new JsonResult();
        Boolean aBoolean = seckillService.setSeckill(secKillDTO);
        if (aBoolean){
            jsonResult.setMsg("添加成功！");
            jsonResult.setCode("200");
        }
        else{
            jsonResult.setMsg("添加失败！");
            jsonResult.setCode("0");
        }
        return jsonResult.getMap();
    }
}
